package com.hsl.test.utils;

import com.hsl.test.aop.TAutowired;
import com.hsl.test.aop.TService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * @author hsl
 * @Data 2021/12/14
 * @Desc
 */
@TService
public class ProxyFactory {
    
    @TAutowired
    private TransactionManager transactionManager;

    public Object getJdkProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    //开启事务
                    transactionManager.beginTransaction();
                    // 执行方法
                    result = method.invoke(obj, args);
                    //提交事务
                    transactionManager.commit();
                } catch (Exception e) {
                    System.out.println("方法执行异常：" + e.getMessage());
                    // 事务回滚
                    transactionManager.rollback();
                    //向上层抛出异常
                    throw e;
                }
                return result;
            }
        });
    }
}
